package com.lovelc.cn;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;

/**
 * @ClassName ObserverFriends
 * @Description TODO
 * @Author huangjh5
 * @Date 2021/1/5 13:01
 */

public class ObserverFriends extends BaseRegionObserver {


    @Override
    public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {
        HTableInterface user = e.getEnvironment().getTable(TableName.valueOf("user"));
        //进行删除的时候 t1->t2 的删除 ，外加 t2 -> t1的也进行删除
        //t1
        NavigableMap<byte[], List<Cell>> familyCellMap = delete.getFamilyCellMap();

        //拿到friends 列族
        List<Cell> cells = familyCellMap.get(Bytes.toBytes("friends"));

        for (byte[] bytes : familyCellMap.keySet()) {
            System.out.println("列族 ：" + Bytes.toString(bytes));
        }

        //t2
        for (Cell cell : cells) {
            //列信息
            byte[] column = CellUtil.cloneQualifier(cell);
            //rowkey信息
            byte[] rowKey = CellUtil.cloneRow(cell);


            System.out.println("列信息"+ Bytes.toString(column));
            System.out.println("rowkey信息"+ Bytes.toString(rowKey));

            //存在就进行删除
            if (user.exists(new Get(column).addColumn(Bytes.toBytes("friends"), rowKey))) {
                Delete another = new Delete(column).addColumn(Bytes.toBytes("friends"), rowKey);
                user.delete(another);
            }else{
                System.out.println(  Bytes.toString(column) + " friends  " + Bytes.toString(rowKey) + "不存在 不进行删除");
            }
        }
        //记得关闭  不然会不进行执行 延迟提交。。
        user.close();
    }
}
